<style>
.page {
  text-align: center;
  margin-top: 7px;
}
.page1 {
  margin-top: 15px;
  margin-left: 15px;
  float: none;
}
.a11 {
  margin-top: 10px;
}
.page2 {
  text-align: center;
  margin-top: 15px;
  overflow-x: hidden;
  overflow-y: auto;
  table-layout: fixed;
}
.page4 {
  float: left;
  margin-top: 15px;
  margin-left: 15px;
}
.page14 {
  float: left;
  margin-top: 15px;
}
.ivu-table-overflowX {
  overflow-x: hidden;
}
.demo-drawer-profile {
  font-size: 14px;
}
.demo-drawer-profile .ivu-col {
  margin-bottom: 12px;
}
.myrole {
  margin-left: 10px;
}
.in1 {
  margin-left: 7px;
}
</style>
<template>
  <div>
    <Breadcrumb>
      <BreadcrumbItem to="/main/myInfo">
        <e-icon icon-name="el-icon-s-home"></e-icon>主页
      </BreadcrumbItem>
      <BreadcrumbItem>
        <e-icon icon-name="fa fa-book"></e-icon>教学管理
      </BreadcrumbItem>
      <BreadcrumbItem>学生管理 </BreadcrumbItem>
    </Breadcrumb>

    <Divider />

    <Button type="primary" icon="md-person-add" @click="open">添加学生</Button>

    <Modal
      ref="modal1"
      :loading="isLoading"
      v-model="modal1"
      title="添加学生"
      @on-ok="addStudent('studentPo')"
      @on-cancel="cancel"
    >
      <Form
        ref="studentPo"
        :model="studentPo"
        :rules="ruleValidate"
        :label-width="80"
      >
        <FormItem label="学生学号" prop="code">
          <Input
            clearable
            v-model="studentPo.code"
            placeholder="请输入学生学号"
          ></Input>
        </FormItem>
        <FormItem label="学生名称" prop="name">
          <Input
            clearable
            v-model="studentPo.name"
            placeholder="请输入学生名称"
          ></Input>
        </FormItem>
        <FormItem label="学生性别" prop="sex">
          <RadioGroup v-model="studentPo.sex">
            <Radio label="0" border> 女 </Radio>
            <Radio label="1" border> 男 </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="手机号码" prop="mobile">
          <Input
            clearable
            v-model="studentPo.mobile"
            placeholder="请输入学生号码"
          ></Input>
        </FormItem>
        <FormItem label="学生班级" prop="clazzName">
          <InputGrid
            v-model="studentPo.clazzName"
            placeholder="请选择班级名称"
            :requestConfig="{
              url: '/clazzCourseTeacher/qryClazzPaged',
              method: 'POST',
            }"
            :pagination="true"
            :columns="[
              { label: '班级名称', key: 'name' },
              { label: '班级代码', key: 'code' },
              { label: '状态', key: 'statusName' },
            ]"
            :showIndex="true"
            keywordKey="name"
            :panelStyle="'width:410px'"
            :otherParams="{}"
            :showSelect="false"
            @row-select-event="getClazzSelected"
          />
        </FormItem>
        <FormItem label="学生账号" prop="userId">
          <Select
            v-model="studentPo.userId"
            clearable
            placeholder="请选择学生账号"
            @clear="handleClearUser"
            style="width: 410px"
          >
            <Option v-for="item in selectUser" :key="item.id" :value="item.id">
              {{ item.value }}
            </Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      ref="modal2"
      :loading="isLoading"
      v-model="modal2"
      title="修改学生"
      @on-ok="updateStudent('studentPo2')"
      @on-cancel="cancel"
    >
      <Form
        ref="studentPo2"
        :model="studentPo"
        :rules="ruleValidate2"
        :label-width="80"
      >
        <FormItem label="学生学号" prop="code">
          <Input
            clearable
            v-model="studentPo.code"
            placeholder="请输入学生学号"
          ></Input>
        </FormItem>
        <FormItem label="学生名称" prop="name">
          <Input
            clearable
            v-model="studentPo.name"
            placeholder="请输入学生名称"
          ></Input>
        </FormItem>
        <FormItem label="学生性别" prop="sex">
          <RadioGroup v-model="studentPo.sex">
            <Radio :label="0" border> 女 </Radio>
            <Radio :label="1" border> 男 </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="手机号码" prop="mobile">
          <Input
            clearable
            v-model="studentPo.mobile"
            placeholder="请输入学生号码"
          ></Input>
        </FormItem>
        <FormItem label="学生班级" prop="clazzName">
          <InputGrid
            v-model="studentPo.clazzName"
            placeholder="请选择班级名称"
            :requestConfig="{
              url: '/clazzCourseTeacher/qryClazzPaged',
              method: 'POST',
            }"
            :pagination="true"
            :columns="[
              { label: '班级名称', key: 'name' },
              { label: '班级代码', key: 'code' },
              { label: '状态', key: 'statusName' },
            ]"
            :showIndex="true"
            keywordKey="name"
            :panelStyle="'width:550px'"
            :otherParams="{}"
            :showSelect="false"
            @row-select-event="getClazzSelected"
          />
        </FormItem>
        <FormItem label="学生账号" prop="userId">
          <Select
            v-model="studentPo.userId"
            clearable
            placeholder="请选择学生账号"
            @clear="handleClearUser"
            style="width: 410px"
          >
            <Option v-for="item in selectUser" :key="item.id" :value="item.id">
              {{ item.value }}
            </Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>

    <Input
      class="in1"
      clearable
      v-model="studentQo.code"
      placeholder="请输入学生学号"
      style="width: 200px"
    />
    <Input
      class="in1"
      clearable
      v-model="studentQo.name"
      placeholder="请输入学生姓名"
      style="width: 200px"
    />
    <Select
      class="in1"
      v-model="studentQo.sex"
      clearable
      style="width: 200px"
      placeholder="请选择学生性别"
    >
      <Option value="0">男</Option>
      <Option value="1">女</Option>
    </Select>

    <Select
      class="in1"
      v-model="studentQo.clazzId"
      clearable
      style="width: 200px"
      placeholder="请选择学生班级"
    >
      <Option v-for="(item, index) in clazzQo" :key="index" :value="item.id">{{
        item.value
      }}</Option>
    </Select>

    <Button class="in1" type="primary" icon="ios-search" @click="selectStudent"
      >搜索</Button
    >
    <Button class="in1" icon="md-close" @click="reset">清除</Button>
    <Table
      style="width: 100%"
      context-menu
      show-context-menu
      class="page2"
      ref="selection"
      border
      :columns="columns1"
      :data="data.records"
      @on-selection-change="checkStudent"
      @on-contextmenu="handleContextMenu"
      :loading="loading"
    >
      <template slot="contextMenu">
        <DropdownItem @click.native="handleContextMenuEdit">修改</DropdownItem>
        <DropdownItem
          @click.native="handleContextMenuDelete"
          style="color: #ed4014"
          >删除</DropdownItem
        >
      </template>
    </Table>

    <Upload
      class="page14"
      ref="upload"
      :before-upload="handleUpload"
      accept=".xls"
      :format="['xls']"
      action="http://localhost:8090/student/importExcel"
      :on-success="handleUploadSuccess"
      :show-upload-list="false"
      :on-error="handleUploadError"
      :on-format-error="handleFormatError"
    >
      <Button  icon="ios-cloud-upload">上传文件</Button>
    </Upload>
    <Button
      class="page4"
      type="primary"
      ghost
      @click="download"
      icon="ios-cloud-download"
      >下载模板</Button
    >

    <Button
      class="page1"
      type="error"
      ghost
      @click="ifDeleteAll"
      icon="ios-trash"
      >删除所选</Button
    >
        <div class="a11" v-if="fileList !== null">
      文件 : {{ fileList.name }}
      <Button  @click="upload" :loading="loadingStatus">{{
        loadingStatus ? "正在上传" : "点击上传"
      }}</Button>
    </div>
    <Page
      class="page"
      :total="data.total"
      :current="data.current"
      :page-size="6"
      :page-size-opts="pagesizeopts"
      @on-change="changePage"
      @on-page-size-change="sizeChange"
      show-elevator
      show-total
      show-sizer
    />
    <Modal v-model="value4" width="450">
      <p slot="header">
        <Icon type="ios-information-circle"></Icon>
        <span>学生详情信息</span>
      </p>
    </Modal>
  </div>
</template>

<script>
import InputGrid from "@/components/InPutGrid/InPutGrid.vue";
export default {
  components: {
    InputGrid,
  },
  data() {
    return {
      loadingStatus: false,
      // 上传文件列表
      fileList: null,
      //表格加载
      loading: true,
      //树形组件需要的数据对应
      defaultProps: {
        children: "children",
        label: "name",
      },
      //学生详情
      details: {},
      //每页展示条数
      pagesizeopts: [6, 10, 15, 20],
      //存放查询学生studentVo的信息
      data: {},
      //数据库用户的集合
      selectUser: [],
      //查询学生的查询条件
      studentQo: {
        pageSize: 6,
        pageIndex: 1,
      },
      //添加学生确定按钮的一直加载，添加信息不符合要求时不会关闭弹窗
      isLoading: true,
      //添加学生->是否打开弹窗
      modal1: false,
      //修改学生->否打开弹窗
      modal2: false,
      //添加学生时存储学生的信息
      studentPo: {
        clazzName: "",
      },
      //班级候选表
      clazzQo: "",
      //存储多选时学生id
      studnetIdList: [],
      //学生详情页面的style
      pStyle: {
        fontSize: "16px",
        color: "rgba(0,0,0,0.85)",
        lineHeight: "24px",
        display: "block",
        marginBottom: "16px",
      },
      //是否显示学生详情页
      value4: false,
      //右键表格的行数
      contextLine: "",
      //添加学生时的表单验证
      ruleValidate: {
        code: [
          { required: true, message: "学生代码不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" },
        ],
        sex: [
          {
            required: true,
            message: "学生性别不能为空",
            trigger: "blur",
          },
        ],
        clazzName: [
          {
            required: true,
            message: "学生班级不能为空",
            trigger: "blur",
          },
        ],
      },
      //修改学生时的表单验证
      ruleValidate2: {
        code: [
          { required: true, message: "学生代码不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" },
        ],
        clazzName: [
          {
            required: true,
            message: "学生班级不能为空",
            trigger: "blur",
          },
        ],
      },
      //学生的表格
      columns1: [
        {
          width: 60,
          type: "selection",
        },
        {
          title: "ID",
          key: "id",
          width: 60,
        },
        {
          title: "学生学号",
          key: "code",
          width: 200,
        },
        {
          title: "学生名称",
          key: "name",
          width: 200,
        },
        {
          title: "所属班级",
          key: "clazzName",
          width: 220,
        },
        {
          title: "所属账号",
          key: "userAccount",
          width: 160,
        },
        {
          title: "操作",
          align: "center",
          render: (h, params) => {
            let ifStatus;
            if (params.row.status == 0) {
              ifStatus = true;
            } else if (params.row.status == 1) {
              ifStatus = false;
            }
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    icon: "md-glasses",
                  },
                  style: {
                    id: "btn1",
                    marginLeft: "15px",
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                    },
                  },
                },
                "详情"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "info",
                    size: "small",
                    icon: "md-create",
                  },
                  style: {
                    marginLeft: "15px",
                  },
                  on: {
                    click: () => {
                      this.open2(params.index);
                    },
                  },
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                    icon: "ios-trash-outline",
                  },
                  style: {
                    marginLeft: "15px",
                  },
                  on: {
                    click: () => {
                      this.ifDelete(params.index);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
    };
  },
  created() {
    //页面加载时
    //查询学生
    this.selectStudent();
    //查询用户
    this.userList();
    //查询班级
    this.clazzList();
  },
  methods: {
    //弹出框点取消时
    cancel() {},
    //查询班级
    clazzList() {
      this.$axios
        .get("/student/listAllClazz")
        .then((result) => {
          this.clazzQo = result.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //查询学生
    selectStudent() {
      this.loading = true;
      this.$axios
        .post("/student/listPaged", this.studentQo)
        .then((result) => {
          this.data = result.data.data;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取用户列表，以便搜索用户时选择
    userList() {
      this.$axios
        .get("/student/listAllUser", {
          params: {
            studentId: null,
          },
        })
        .then((result) => {
          this.selectUser = result.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //选择班级
    getClazzSelected(row) {
      this.studentPo.clazzId = row.id;
      console.log(this.studentPo.clazzId);
      this.studentPo.clazzName = row.name;
    },
    getstudentQoClazz(row) {
      this.studentQo.clazzId = row.id;
      console.log(this.studentQo.clazzId);
      this.studentQo.clazzName = row.name;
    },
    //点击清空下拉框按钮时触发
    handleClearUser() {
      this.studentPo.userId = null;
    },
    //打开添加学生弹窗
    open() {
      this.userList();
      this.modal1 = true;
    },
    //打开修改学生弹窗
    open2(index) {
      this.$axios
        .get("/student/listAllUser", {
          params: {
            studentId: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.selectUser = result.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
      this.$axios
        .get("/student/details", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.studentPo = {
            clazzName: "",
          };
          this.studentPo = result.data.data;
          console.log(this.studentPo);
          this.modal2 = true;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //添加学生
    addStudent(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的学生信息是否正确
        if (valid) {
          this.$axios
            .post("/student/addStudent", this.studentPo)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: "添加成功",
                });
                //插入数据成功更新查询
                this.selectStudent();
                //清空上次保存的学生信息
                this.studentPo = { clazzName: "" };
                this.userList();
                this.modal1 = false;
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "添加失败",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //改变页数时
    changePage(e) {
      //变更查询时的页数条件
      this.studentQo.pageIndex = e;
      this.selectStudent();
    },
    //多选选中学生
    checkStudent(e) {
      //先将选中id设为空，以免重复添加id
      this.studentIdList = [];
      console.log(e);
      //循环添加id
      e.forEach((element) => {
        this.studentIdList.push(element.id);
      });
      console.log(this.studentIdList);
    },

    //弹框问是否删除多选
    ifDeleteAll() {
      if (
        this.studentIdList !== undefined &&
        this.studentIdList !== null &&
        this.studentIdList.length > 0
      ) {
        this.$Modal.confirm({
          title: "警告",
          content: "<p>你真的要删除这些学生么?</p>",
          onOk: () => {
            this.deleteCheckStudent();
          },
          onCancel: () => {},
        });
      } else {
        this.$Message.warning({
          top: 30,
          duration: 2.5,
          background: true,
          content: "您未选择任何学生",
        });
      }
    },
    //删除选中的学生
    deleteCheckStudent() {
      this.$axios
        .post("/student/deleteCheckStudent", this.studentIdList)
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectStudent();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //弹框问是否删除
    ifDelete(index) {
      this.$Modal.confirm({
        title: "警告",
        content: "<p>你真的要删除该学生么?</p>",
        onOk: () => {
          this.remove(index);
        },
        onCancel: () => {},
      });
    },
    //删除单个学生
    remove(index) {
      this.$axios
        .get("/student/deleteStudent", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectStudent();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //学生详情信息
    show(index) {
      this.value4 = true;
      this.$axios
        .get("/student/details", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.details = result.data.data;
          console.log(this.details);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //修改学生信息
    updateStudent(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的学生信息是否正确
        if (valid) {
          this.$axios
            .post("/student/updateStudent", this.studentPo)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: "修改成功",
                });
                //插入数据成功更新查询
                this.selectStudent();
                //清空上次保存的学生信息
                this.studentPo = { clazzName: "" };
                this.modal2 = false;
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "修改失败",
                });
              }
              console.log(result.data);
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //关闭弹窗时，清除studentPo信息
    cancel() {
      this.studentPo = { clazzName: "" };
    },
    //右键表格时得到右键表格的位置
    handleContextMenu(row) {
      const index = this.data.records.findIndex(
        (item) => item.name === row.name
      );
      this.contextLine = index;
    },
    //右键修改信息
    handleContextMenuEdit() {
      this.open2(this.contextLine);
    },
    //右键删除学生
    handleContextMenuDelete() {
      this.$Modal.confirm({
        title: "警告",
        content: "<p>你真的要删除该学生么?</p>",
        onOk: () => {
          this.remove(this.contextLine);
        },
        onCancel: () => {},
      });
    },
    //改变页面显示数据大小后
    sizeChange(e) {
      this.studentQo.pageSize = e;
      this.selectStudent();
    },
    //清除查询条件
    reset() {
      (this.studentQo = {
        pageSize: this.studentQo.pageSize,
        pageIndex: 1,
      }),
        this.selectStudent();
    },
    upload() {
      this.loadingStatus = true;
      this.$refs.upload.post(this.fileList);
      setTimeout(() => {
        this.fileList = null;
        this.loadingStatus = false;
      }, 1000);
    },
    handleUploadSuccess(res, file, fileList) {
      console.log(res);
      if (res.code === 0) {
        this.$Message.success({
          duration: 2.5,
          background: true,
          content: "上传成功",
        });
        this.selectStudent();
      } else {
        this.$Message.error({
          duration: 2.5,
          background: true,
          content: res.msg,
        });
      }
    },
    handleUploadError(err, file, fileList) {
      this.$Message.error({
        duration: 2.5,
        background: true,
        content: err,
      });
    },
    handleFormatError(file, fileList) {
      this.$Message.error({
        duration: 2.5,
        background: true,
        content: "文件" + file.name + "不符合.xls后缀格式",
      });
    },
    handleUpload(file) {
      this.fileList = file;
      return false;
    },
    download() {
      var _this = this;
      this.loading = true;
      fetch("http://localhost:8090//student/downloadTemplate", {
        method: "POST",
      }).then((res) => {
        _this.loading = false;
        res.blob().then(function (obj) {
          let fileName = "学生管理.xls";
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(obj, fileName);
          } else {
            const anchor = document.createElement("a");
            const body = document.querySelector("body");
            anchor.href = window.URL.createObjectURL(obj);
            anchor.download = fileName;
            anchor.style.display = "none";
            body.appendChild(anchor);
            anchor.click();
            body.removeChild(anchor);
            window.URL.revokeObjectURL(anchor.href);
          }
        });
      });
    },
  },
};
</script>